package com.ruicar.afs.cloud.contract.gateway.processor.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.common.core.dynamicrequest.DynamicRequest;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.holder.TransRequestContextHolder;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.enums.SystemType;
import com.ruicar.afs.cloud.contract.gateway.beans.*;
import com.ruicar.afs.cloud.contract.gateway.dto.PageInfo;
import com.ruicar.afs.cloud.contract.gateway.entity.GateWayDetectRecord;
import com.ruicar.afs.cloud.contract.gateway.entity.GateWayOutDataMapping;
import com.ruicar.afs.cloud.contract.gateway.entity.GateWaySystemMapping;
import com.ruicar.afs.cloud.contract.gateway.enums.*;
import com.ruicar.afs.cloud.contract.gateway.mapper.GateWayDetectRecordMapper;
import com.ruicar.afs.cloud.contract.gateway.processor.ProcessorHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


/**
 * The type DefaultApiProcessor
 * <p>Description: </p>
 *
 * @author Fzero
 * @version 1.0
 * @date Created on 2020.07.20 21:17:41
 * @since 1.0
 */
@Component
@Slf4j
@AllArgsConstructor
public class DefaultApiProcessor implements ApiProcessor{

    private static final String NOT_EXISTS_DEC_VALUE="----------";
    /**
     * Process name processor name
     *
     * @return the processor name
     */
    @Override
    public ProcessorName processName() {
        return ProcessorName.DEFAULT;
    }

    private static final ThreadPoolExecutor EXECUTOR = ThreadUtil.newExecutor(3,6);
    /**
     * Dynamic request
     * <p>Description: </p>
     */
    private final DynamicRequest dynamicRequest;

    private final GateWayDetectRecordMapper gateWayDetectRecordMapper;

    /**
     * Page process gate way response
     *
     * @param params    params
     * @param apiDefine api define
     * @return the gate way response
     */
    private GateWayResponse pageProcess(JSON params, ApiDefine apiDefine){
        List<PageResponseInfo> pageInfoList = new ArrayList<>();
        PageInfo requestPageInfo = ProcessorHelper.genRequestPageInfo(params,apiDefine);
        for (SysPageInfo sysPageInfo : ProcessorHelper.genSystemPageInfos(apiDefine,requestPageInfo)) {
            String result=null;
            if(apiDefine.getGateWayApiMapping().getStatus()== ApiStatus.MOCK||sysPageInfo.getSystemDefine().getGateWaySystemMapping().getStatus()==ApiStatus.MOCK){
                result = sysPageInfo.getSystemDefine().getGateWaySystemMapping().getMockJson();
                log.info("当前请求接口===>[{}],接口处于mock状态返回mock数据",sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl());
            }else {
                log.info("当前请求接口===>[{}],系统类型[{}],跳过[{}]条,加载[{}]条", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), sysPageInfo.getSkipCount(), sysPageInfo.getLoadCount());
                GateWaySystemMapping gateWaySystemMapping = sysPageInfo.getSystemDefine().getGateWaySystemMapping();
                JSON systemRequestJson = ProcessorHelper.genJSONObjectRequestParam(params, sysPageInfo.getSystemDefine().getParamInMappings());
                JSONUtil.putByPath(systemRequestJson, gateWaySystemMapping.getSkipCountExpress(), sysPageInfo.getSkipCount());
                JSONUtil.putByPath(systemRequestJson, gateWaySystemMapping.getLoadCountExpress(), sysPageInfo.getLoadCount());
                List<String> extParams = StrUtil.splitTrim(sysPageInfo.getSystemDefine().getGateWaySystemMapping().getExtParams(), ";");
                List<String> extHeaders = StrUtil.splitTrim(sysPageInfo.getSystemDefine().getGateWaySystemMapping().getExtHeaders(), ";");
                Map<String, List<String>> headers = new HashMap<>();
                for (String string : extParams) {
                    String[] strings = string.split("=");
                    if (strings.length == 2) {
                        JSONUtil.putByPath(systemRequestJson, strings[0], strings[1]);
                    }
                }
                for (String string : extHeaders) {
                    String[] strings = string.split("=");
                    if (strings.length == 2) {
                        headers.put(strings[0], StrUtil.splitTrim(strings[1], ","));
                    }
                }
                if (gateWaySystemMapping.getTargetUrl().startsWith("lb://")) {
                    String targetUri = sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl().replaceFirst("lb://", "");
                    String serviceName = targetUri.substring(0, targetUri.indexOf(StrUtil.SLASH));
                    String requestUri = targetUri.substring(targetUri.indexOf(StrUtil.SLASH));
                    requestUri = ProcessorHelper.genRequestUri(params, requestUri);
                    log.info("处理后的Uri为[{}],请求类型为{}", requestUri, gateWaySystemMapping.getRequestMethod());
                    try {
                        if (RequestType.GET == gateWaySystemMapping.getRequestMethod()) {
                            Map<String, String> requestParam = ProcessorHelper.convertJsonToMap(systemRequestJson);
                            log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), requestParam);
                            result = dynamicRequest.get(serviceName, requestUri, requestParam);
                        } else if (RequestType.POST == gateWaySystemMapping.getRequestMethod()) {
                            log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), systemRequestJson);
                            result = dynamicRequest.post(serviceName, requestUri, systemRequestJson);
                        } else {
                            log.warn("不支持的请求方式,系统配置ID[{}],请求URI[{}]", gateWaySystemMapping.getId(), gateWaySystemMapping.getTargetUrl());
                        }
                    } catch (Exception e) {
                        log.error("", e);
                        result = "request error";
                    }
                } else {
                    String requestUri = sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl();
                    requestUri = ProcessorHelper.genRequestUri(params, requestUri);
                    HttpResponse httpResponse = null;
                    log.info("处理后的Uri为[{}],请求类型为{}", requestUri, gateWaySystemMapping.getRequestMethod());
                    try {
                        if (RequestType.GET == gateWaySystemMapping.getRequestMethod()) {
                            Map<String, Object> requestParam = ProcessorHelper.convertJsonToObjectMap(systemRequestJson);
                            log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), requestParam);
                            httpResponse = HttpUtil.createGet(requestUri).header(headers).form(ProcessorHelper.convertJsonToObjectMap(systemRequestJson)).execute();
                        } else if (RequestType.POST == gateWaySystemMapping.getRequestMethod()) {
                            log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), systemRequestJson);
                            httpResponse = HttpUtil.createPost(requestUri).header(headers).body(systemRequestJson).execute();
                        } else {
                            log.warn("不支持的请求方式,系统配置ID[{}],请求URI[{}]", gateWaySystemMapping.getId(), gateWaySystemMapping.getTargetUrl());
                        }
                    } catch (Exception e) {
                        log.error("", e);
                    }
                    if (httpResponse == null || httpResponse.getStatus() != 200) {
                        result = "server error";
                    } else {
                        result = httpResponse.body();
                    }
                }
            }
            if(JSONUtil.isJson(result)&&ProcessorHelper.checkRequest(JSONUtil.parse(result),sysPageInfo.getSystemDefine().getGateWaySystemMapping())){
                JSON json = JSONUtil.parse(result);
                PageResponseInfo pageResponseInfo = new PageResponseInfo();
                pageResponseInfo.setOnlyTotal(sysPageInfo.isOnlyTotal());
                pageResponseInfo.setTotal(Long.valueOf(JSONUtil.getByPath(json,sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTotalExpress()).toString()));
                pageResponseInfo.setSystemType(sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType());
                JSONArray jsonArray = (JSONArray) JSONUtil.getByPath(json,sysPageInfo.getSystemDefine().getGateWaySystemMapping().getRecodeExpress());
                pageResponseInfo.setArray(new JSONArray());
                for (int index = 0; index < jsonArray.size(); index++) {
                    JSON re =null;
                    if(sysPageInfo.getSystemDefine().getOutDataMappings()==null||sysPageInfo.getSystemDefine().getOutDataMappings().size()==0){
                        re = jsonArray.getJSONObject(index);
                    }else {
                        re  = ProcessorHelper.convertOut(jsonArray.getJSONObject(index),sysPageInfo.getSystemDefine().getOutDataMappings(),pageResponseInfo.getSystemType());
                    }
                    re.putByPath("_systemType", AfsEnumUtil.key(pageResponseInfo.getSystemType()));
                    pageResponseInfo.getArray().add(re);
                }
                pageInfoList.add(pageResponseInfo);
            }else{
                log.info("获取接口[{}]数据失败,系统类型[{}]，接口返回值[{}]",sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(),sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(),result);
            }
        }
        PageInfo rtnPageInfo = new PageInfo();
        rtnPageInfo.setPageIndex(requestPageInfo.getPageIndex());
        rtnPageInfo.setPageSize(requestPageInfo.getPageSize());
        rtnPageInfo.setRecords(new JSONArray());
        rtnPageInfo.setTotal(pageInfoList.stream().mapToLong(PageResponseInfo::getTotal).sum());
        rtnPageInfo.setTotalInfo(pageInfoList.stream().collect(Collectors.toMap(PageResponseInfo::getSystemType,PageResponseInfo::getTotal)));
        for (PageResponseInfo pageResponseInfo:pageInfoList) {
            if(pageResponseInfo.isOnlyTotal()){
                continue;
            }
            for (int index = 0; index < pageResponseInfo.getArray().size(); index++) {
                if(rtnPageInfo.getRecords().size()<requestPageInfo.getPageSize()){
                    rtnPageInfo.getRecords().add(pageResponseInfo.getArray().getJSONObject(index));
                }else {
                    break;
                }
            }
        }
        if(apiDefine.getGateWayApiMapping().getResponseType()== ResponseType.WRAPPER) {
            return new GateWayResponse(JSONObject.toJSONString(IResponse.success(rtnPageInfo)));
        }else {
            return new GateWayResponse(JSONObject.toJSONString(rtnPageInfo));
        }
    }

    private GateWayResponse dataProcess(JSON params, ApiDefine apiDefine){
        SystemType targetSystem = SystemType.NONE;
        String detectValue =null;
        if(StringUtils.isNotEmpty(apiDefine.getGateWayApiMapping().getSystemDetectExpress())){
            Object object = JSONUtil.getByPath(params,apiDefine.getGateWayApiMapping().getSystemDetectExpress());
            detectValue = object==null? NOT_EXISTS_DEC_VALUE:(String)object;
            List<GateWayDetectRecord> detectRecordList = gateWayDetectRecordMapper.selectList(Wrappers.<GateWayDetectRecord>lambdaQuery().eq(GateWayDetectRecord::getDetectValue,detectValue));
            if(CollectionUtil.isNotEmpty(detectRecordList)){
                targetSystem = detectRecordList.get(0).getSystemType();
            }
        }
        Map<SystemType,List<SystemDefine>> defines = new HashMap<>();
        if(targetSystem==SystemType.NONE){
            log.info("未找到探测值，将从所有配置系统获取数据");
            defines.putAll(apiDefine.getTypeListMap());
        }else{
            Assert.isTrue(apiDefine.getTypeListMap().containsKey(targetSystem),"配置系统不包含通过探测获取到的系统");
            defines.put(targetSystem,apiDefine.getTypeListMap().get(targetSystem));
        }
        Map<SystemType, cn.hutool.json.JSONObject> systemRtnMap = new HashMap<>();
        defines.entrySet().stream()
                .filter(entry->CollectionUtil.isNotEmpty(entry.getValue()))
                .forEach(entry->{
                    try {
                        systemRtnMap.put(entry.getKey(), JSONUtil.createObj());
                        CountDownLatch countDownLatch = new CountDownLatch(entry.getValue().size());
                        for (int index = 0; index < entry.getValue().size(); index++) {
                            RequestRunner requestRunner = RequestRunner.builder()
                                    .countDownLatch(countDownLatch)
                                    .dynamicRequest(dynamicRequest)
                                    .systemClientInfo(TransRequestContextHolder.getClientInfo())
                                    .transLogHeader(TransRequestContextHolder.getTransLogHeader())
                                    .jsonObject(systemRtnMap.get(entry.getKey()))
                                    .systemDefine(entry.getValue().get(index))
                                    .systemType(entry.getKey())
                                    .params(params)
                                    .build();
                            EXECUTOR.execute(requestRunner);
                        }
                        countDownLatch.await();
                    }catch (Exception e){
                        log.error("",e);
                        systemRtnMap.remove(entry.getKey());
                    }
        });
        log.info("共处理[{}]个系统数据,包含数据系统为[{}]",systemRtnMap.size(),systemRtnMap.keySet());

       List<Map.Entry<SystemType,cn.hutool.json.JSONObject>> list =  systemRtnMap.entrySet()
                .stream()
                .filter(entry-> entry.getValue().getJSONArray("_requestError").size()==0)
               .collect(Collectors.toList());
        log.info("过滤后符合要求记录共{}条",list.size());
        if(list.size()==1){
//            if(!StringUtils.isEmpty(detectValue)&&!StringUtils.equals(detectValue,NOT_EXISTS_DEC_VALUE)){
//                ProcessorHelper.saveDetectRecord(detectValue,list.get(0).getKey());
//            }
            List<GateWayOutDataMapping> outDataMappings = apiDefine
                    .getTypeListMap()
                    .get(list.get(0).getKey())
                    .stream()
                    .map(SystemDefine::getOutDataMappings)
                    .flatMap(Collection::stream)
                    .collect(Collectors.toList());
            JSON json = null;
            if(outDataMappings.size()==0){
                list.get(0).getValue().remove("_requestError");
                json =  list.get(0).getValue();
            }else {
                json = ProcessorHelper.deepConvert( list.get(0).getValue(),outDataMappings);
            }

            if(apiDefine.getGateWayApiMapping().getResponseType()== ResponseType.WRAPPER) {
                return new GateWayResponse(JSONObject.toJSONString(IResponse.success(JSONObject.parse(json.toStringPretty()))));
            }else {
                return new GateWayResponse(JSONObject.toJSONString(JSONObject.parse(json.toStringPretty()),SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteMapNullValue));
            }
        }else if(list.size()>1){
            return  new GateWayResponse(HttpStatus.BAD_REQUEST, MediaType.APPLICATION_JSON, JSONObject.toJSONString(IResponse.fail("无法确定数据来源系统，不返回任何数据")));
        }else{
            return  new GateWayResponse(JSONObject.toJSONString(IResponse.success(new JSONObject())));
        }
    }

    private GateWayResponse scriptProcess(JSON params, ApiDefine apiDefine){

        Map<SystemType,List<SystemDefine>> defines = new HashMap<>();
        defines.putAll(apiDefine.getTypeListMap());
        Map<SystemType, cn.hutool.json.JSONObject> systemRtnMap = new HashMap<>();
        defines.entrySet().stream()
                .filter(entry->CollectionUtil.isNotEmpty(entry.getValue()))
                .forEach(entry->{
                    try {
                        systemRtnMap.put(entry.getKey(), JSONUtil.createObj());
                        CountDownLatch countDownLatch = new CountDownLatch(entry.getValue().size());
                        for (int index = 0; index < entry.getValue().size(); index++) {
                            RequestRunner requestRunner = RequestRunner.builder()
                                    .countDownLatch(countDownLatch)
                                    .dynamicRequest(dynamicRequest)
                                    .systemClientInfo(TransRequestContextHolder.getClientInfo())
                                    .transLogHeader(TransRequestContextHolder.getTransLogHeader())
                                    .jsonObject(systemRtnMap.get(entry.getKey()))
                                    .systemDefine(entry.getValue().get(index))
                                    .systemType(entry.getKey())
                                    .params(params)
                                    .build();
                            EXECUTOR.execute(requestRunner);
                        }
                        countDownLatch.await();
                    }catch (Exception e){
                        log.error("",e);
                        systemRtnMap.remove(entry.getKey());
                    }
                });
        log.info("共处理[{}]个系统数据,包含数据系统为[{}]",systemRtnMap.size(),systemRtnMap.keySet());

        List<Map.Entry<SystemType,cn.hutool.json.JSONObject>> list =  systemRtnMap.entrySet()
                .stream()
                .filter(entry-> entry.getValue().getJSONArray("_requestError").size()==0)
                .collect(Collectors.toList());
        log.info("过滤后符合要求记录共{}条",list.size());
        JSONObject jsonObject = new JSONObject();
        for (Map.Entry<SystemType, cn.hutool.json.JSONObject> apiRtn : list) {
            List<GateWayOutDataMapping> outDataMappings = apiDefine
                    .getTypeListMap()
                    .get(apiRtn.getKey())
                    .stream()
                    .map(SystemDefine::getOutDataMappings)
                    .flatMap(Collection::stream)
                    .collect(Collectors.toList());
            JSON json = null;
            if(outDataMappings.size()==0){
                apiRtn.getValue().remove("_requestError");
                json =  apiRtn.getValue();
            }else {
                json = ProcessorHelper.deepConvert( apiRtn.getValue(),outDataMappings);
            }
            if(apiDefine.getGateWayApiMapping().getResponseType()== ResponseType.WRAPPER) {
                jsonObject.put(AfsEnumUtil.key(apiRtn.getKey()),IResponse.success(JSONObject.parse(json.toStringPretty())));
            }else {
                jsonObject.put(AfsEnumUtil.key(apiRtn.getKey()),JSONObject.parse(json.toStringPretty()));
            }
        }
        return new GateWayResponse(jsonObject.toString(SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteMapNullValue));
    }


    private GateWayResponse queryProcess(JSON params, ApiDefine apiDefine){
        List<PageResponseInfo> pageInfoList = new ArrayList<>();
        PageInfo requestPageInfo = ProcessorHelper.genRequestEmptyPageInfo(params,apiDefine);
        for (SysPageInfo sysPageInfo : ProcessorHelper.genSystemPageInfos(apiDefine,requestPageInfo)) {
            String result=null;
            if(apiDefine.getGateWayApiMapping().getStatus()== ApiStatus.MOCK||sysPageInfo.getSystemDefine().getGateWaySystemMapping().getStatus()==ApiStatus.MOCK){
                result = sysPageInfo.getSystemDefine().getGateWaySystemMapping().getMockJson();
                log.info("当前请求接口===>[{}],接口处于mock状态返回mock数据",sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl());
            }else {
                log.info("当前请求接口===>[{}],系统类型[{}],跳过[{}]条,加载[{}]条", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), sysPageInfo.getSkipCount(), sysPageInfo.getLoadCount());
                GateWaySystemMapping gateWaySystemMapping = sysPageInfo.getSystemDefine().getGateWaySystemMapping();
                JSON systemRequestJson = ProcessorHelper.genJSONObjectRequestParam(params, sysPageInfo.getSystemDefine().getParamInMappings());
                List<String> extParams = StrUtil.splitTrim(sysPageInfo.getSystemDefine().getGateWaySystemMapping().getExtParams(), ";");
                List<String> extHeaders = StrUtil.splitTrim(sysPageInfo.getSystemDefine().getGateWaySystemMapping().getExtHeaders(), ";");
                Map<String, List<String>> headers = new HashMap<>();
                for (String string : extParams) {
                    String[] strings = string.split("=");
                    if (strings.length == 2) {
                        JSONUtil.putByPath(systemRequestJson, strings[0], strings[1]);
                    }
                }
                for (String string : extHeaders) {
                    String[] strings = string.split("=");
                    if (strings.length == 2) {
                        headers.put(strings[0], StrUtil.splitTrim(strings[1], ","));
                    }
                }
                if (gateWaySystemMapping.getTargetUrl().startsWith("lb://")) {
                    String targetUri = sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl().replaceFirst("lb://", "");
                    String serviceName = targetUri.substring(0, targetUri.indexOf(StrUtil.SLASH));
                    String requestUri = targetUri.substring(targetUri.indexOf(StrUtil.SLASH));
                    requestUri = ProcessorHelper.genRequestUri(params, requestUri);
                    log.info("处理后的Uri为[{}],请求类型为{}", requestUri, gateWaySystemMapping.getRequestMethod());
                    try {
                        if (RequestType.GET == gateWaySystemMapping.getRequestMethod()) {
                            Map<String, String> requestParam = ProcessorHelper.convertJsonToMap(systemRequestJson);
                            log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), requestParam);
                            result = dynamicRequest.get(serviceName, requestUri, requestParam);
                        } else if (RequestType.POST == gateWaySystemMapping.getRequestMethod()) {
                            log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), systemRequestJson);
                            result = dynamicRequest.post(serviceName, requestUri, systemRequestJson);
                        } else {
                            log.warn("不支持的请求方式,系统配置ID[{}],请求URI[{}]", gateWaySystemMapping.getId(), gateWaySystemMapping.getTargetUrl());
                        }
                    } catch (Exception e) {
                        log.error("", e);
                        result = "request error";
                    }
                } else {
                    String requestUri = sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl();
                    requestUri = ProcessorHelper.genRequestUri(params, requestUri);
                    HttpResponse httpResponse = null;
                    log.info("处理后的Uri为[{}],请求类型为{}", requestUri, gateWaySystemMapping.getRequestMethod());
                    try {
                        if (RequestType.GET == gateWaySystemMapping.getRequestMethod()) {
                            Map<String, Object> requestParam = ProcessorHelper.convertJsonToObjectMap(systemRequestJson);
                            log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), requestParam);
                            httpResponse = HttpUtil.createGet(requestUri).header(headers).form(ProcessorHelper.convertJsonToObjectMap(systemRequestJson)).execute();
                        } else if (RequestType.POST == gateWaySystemMapping.getRequestMethod()) {
                            log.info("处理后的参数===>请求uri[{}]，目标系统[{}],参数为[{}]", sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(), sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(), systemRequestJson);
                            httpResponse = HttpUtil.createPost(requestUri).header(headers).body(systemRequestJson).execute();
                        } else {
                            log.warn("不支持的请求方式,系统配置ID[{}],请求URI[{}]", gateWaySystemMapping.getId(), gateWaySystemMapping.getTargetUrl());
                        }
                    } catch (Exception e) {
                        log.error("", e);
                    }
                    if (httpResponse == null || httpResponse.getStatus() != 200) {
                        result = "server error";
                    } else {
                        result = httpResponse.body();
                    }
                }
            }
            if(JSONUtil.isJson(result)&&ProcessorHelper.checkRequest(JSONUtil.parse(result),sysPageInfo.getSystemDefine().getGateWaySystemMapping())){
                JSON json = JSONUtil.parse(result);
                PageResponseInfo pageResponseInfo = new PageResponseInfo();
                pageResponseInfo.setOnlyTotal(false);
                pageResponseInfo.setTotal(10000L);
                pageResponseInfo.setSystemType(sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType());
                JSONArray jsonArray = (JSONArray) JSONUtil.getByPath(json,sysPageInfo.getSystemDefine().getGateWaySystemMapping().getRecodeExpress());
                pageResponseInfo.setArray(new JSONArray());
                for (int index = 0; index < jsonArray.size(); index++) {
                    JSON re =null;
                    if(sysPageInfo.getSystemDefine().getOutDataMappings()==null||sysPageInfo.getSystemDefine().getOutDataMappings().size()==0){
                        re = jsonArray.getJSONObject(index);
                    }else {
                        re  = ProcessorHelper.convertOut(jsonArray.getJSONObject(index),sysPageInfo.getSystemDefine().getOutDataMappings(),pageResponseInfo.getSystemType());
                    }
                    re.putByPath("_systemType", AfsEnumUtil.key(pageResponseInfo.getSystemType()));
                    pageResponseInfo.getArray().add(re);
                }
                pageInfoList.add(pageResponseInfo);
            }else{
                log.info("获取接口[{}]数据失败,系统类型[{}]，接口返回值[{}]",sysPageInfo.getSystemDefine().getGateWaySystemMapping().getTargetUrl(),sysPageInfo.getSystemDefine().getGateWaySystemMapping().getSystemType(),result);
            }
        }
        JSONObject jsonObject = new JSONObject();
        if(StringUtils.isEmpty(apiDefine.getGateWayApiMapping().getResponseCodeMapping())||StringUtils.isEmpty(apiDefine.getGateWayApiMapping().getResponseDataMapping())){
            return  new GateWayResponse(HttpStatus.INTERNAL_SERVER_ERROR, MediaType.APPLICATION_JSON, JSONObject.toJSONString(IResponse.fail("配置错误")));
        }
        String[] successCodes = apiDefine.getGateWayApiMapping().getResponseCodeMapping().split("=");
        String responseData=apiDefine.getGateWayApiMapping().getResponseDataMapping();
        jsonObject.put(successCodes[0],successCodes[1]);
        jsonObject.put(responseData,new com.alibaba.fastjson.JSONArray());
        for (PageResponseInfo pageResponseInfo:pageInfoList) {
            for (int index = 0; index < pageResponseInfo.getArray().size(); index++) {
                jsonObject.getJSONArray(responseData).add(pageResponseInfo.getArray().getJSONObject(index));
            }
        }
        return new GateWayResponse(jsonObject.toJSONString());
    }

    /**
     * Process gate way response
     *
     * @param params    params
     * @param apiDefine api define
     * @return the gate way response
     */
    @Override
    public GateWayResponse process(JSON params, ApiDefine apiDefine) {
        if(apiDefine.apiType()== ApiType.PAGE){
            return pageProcess(params,apiDefine);
        }else if(apiDefine.apiType() == ApiType.DATA){
            return dataProcess(params, apiDefine);
        }else if(apiDefine.apiType() == ApiType.QUERY){
            return queryProcess(params, apiDefine);
        }else if(apiDefine.apiType() == ApiType.SCRIPT){
            return scriptProcess(params, apiDefine);
        }
        return  new GateWayResponse(HttpStatus.METHOD_NOT_ALLOWED, MediaType.APPLICATION_JSON, JSONObject.toJSONString(IResponse.fail("不支持的请求类型")));
    }


}
